package com.by.basicgateway.support;

import com.alibaba.fastjson2.JSONObject;
import com.by.basicgateway.dto.ByGatewayAuthentication;
import com.by.basicgateway.enums.RequestorClientTypeEnum;
import com.by.basicgateway.exception.ByAuthenticationServiceException;
import com.by.gatewayhelper.token.TokenHelper;
import com.by.toolkit.enums.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Tian Wei
 * @version 1.0
 * @date 2024/1/1 11:23 AM
 */

@Slf4j
@Component
public class TokenHandlerSupport {

    @Autowired
    @Lazy
    @Qualifier("adminTokenHelper")
    private TokenHelper adminTokenHelper;

    @Autowired
    @Lazy
    @Qualifier("tocTokenHelper")
    private TokenHelper tocTokenHelper;

    @Autowired
    @Lazy
    @Qualifier("wxcpsidebarTokenHelper")
    private TokenHelper wxcpsidebarTokenHelper;


    public ByGatewayAuthentication convertRequestToMyAuthentication(ServerWebExchange exchange, RequestorClientTypeEnum requestorClientTypeEnum) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(requestorClientTypeEnum.getTokenHeaderName());
        if (StringUtils.isEmpty(token)) {
            return new ByGatewayAuthentication(null, null);
        }

        String host = request.getURI().getHost();
        String path = request.getURI().getPath();
        String ip = request.getRemoteAddress().getHostString();
        boolean validParamFlag = requestorClientTypeEnum.getValidParamPredicate().test(headers);
        if (!validParamFlag) {
            log.error("[TokenHandlerSupport][convertRequestToMyAuthentication] 请求头参数丢失,host:{} path:{} ip,{}", host, path, ip);
            throw new ByAuthenticationServiceException(ErrorCodeEnum.REQUEST_HEADER_MISS.getErrorMessage(), ErrorCodeEnum.REQUEST_HEADER_MISS);
        }

        TokenHelper tokenHelper = RequestorClientTypeEnum.TOB_CLIENT.equals(requestorClientTypeEnum)
                ? adminTokenHelper
                : RequestorClientTypeEnum.TOC_CLIENT.equals(requestorClientTypeEnum)
                ? tocTokenHelper
                : wxcpsidebarTokenHelper;
        JSONObject tokenContentMap = tokenHelper.analyzeToken(token);
        requestorClientTypeEnum
                .getTokenParamPredicate()
                .accept(tokenContentMap);

        String userId = tokenContentMap.getString(requestorClientTypeEnum.getUserIdName());
        tokenContentMap.put("clientHeaderValue", requestorClientTypeEnum.getClientHeaderValue());

        ByGatewayAuthentication myAuthentication = new ByGatewayAuthentication(StringUtils.isEmpty(userId) ? null : Long.parseLong(userId), token);
        myAuthentication.setUserDetail(tokenContentMap.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toString())));
        myAuthentication.setRequestorClientTypeEnum(requestorClientTypeEnum);
        return myAuthentication;
    }
}
